//
//  YZWeakTimerTargetObj.m
//  定时器的坑
//
//

#import "YZWeakTimerTargetObj.h"

@interface YZWeakTimerTargetObj()

@property (nonatomic, weak) id aTarget;
@property (nonatomic, assign) SEL aSelector;
@end
/**
 *  该类的作用是用来接管定时器的强引用
 */
@implementation YZWeakTimerTargetObj

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo {
    
    // 创建当前类对象
    YZWeakTimerTargetObj *obj = [[YZWeakTimerTargetObj alloc] init];
    obj.aTarget = aTarget; // 控制器
    obj.aSelector = aSelector; // 控制器的update方法
    
    return [NSTimer scheduledTimerWithTimeInterval:ti target:obj selector:@selector(update:) userInfo:userInfo repeats:yesOrNo];
}

- (void)update:(NSTimer *)timer {
//    NSLog(@"%s", __FUNCTION__);
//    [self.aTarget performSelector:self.aSelector withObject:timer];
    // 获取 IMP
    IMP imp = [self.aTarget methodForSelector:self.aSelector];
    // 将 IMP 转为一个函数指针
    void (*func)(id, SEL) = (void *)imp;
    // 执行 IMP
    func(self.aTarget, self.aSelector);
}

@end
